//
//  ListDataViewController.m
//  9-20
//
//  Created by mac on 16/10/27.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ListDataViewController.h"
#import "ListData.h"
@interface ListDataViewController () <UITableViewDataSource,UITableViewDelegate>
{
    NSArray <ListItemData *> *arr;
    NSInteger i;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation ListDataViewController

- (void)viewDidLoad {
    i = 1;
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self loadData];
    
    
   
}
- (IBAction)onClick:(UIButton *)sender
{
    i++;
    [self loadData];
}

- (void)loadData
{
   NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://xl18z.cn/list.php?page=%ld",i]];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
            {
                                      
                NSString *string = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
                NSLog(@"%@",string);
                NSLog(@"i = %ld",i);
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                                      
                ListData *d = [[ListData alloc] initWithDictionary:dict];
                
                    dispatch_async(dispatch_get_main_queue(), ^{
                                          
                        if(d.errcode == 0)
                        {
                            arr = d.record;
                            [self.tableView reloadData];
                            NSLog(@"count:%ld",arr.count);
                        }
                        else
                        {
                            NSLog(@"%@",d.errinfo);
                        }
                                          
                    });
                
               
            }];
        [task resume];
}
    


- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    ListItemData *itemData =  arr[indexPath.row];

    cell.textLabel.text = itemData.name;
    cell.detailTextLabel.text = itemData.tel;
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
